<template>
  <div class="merchant-dashboard">
    <!-- 数据概览卡片 -->
    <div class="data-overview-cards w-full">
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <!-- 营业收入 -->
        <a-card class="stat-card revenue-card" :loading="loading">
          <div class="flex items-center justify-between">
            <div>
              <div class="text-gray-500 dark:text-gray-300 mb-2">营业收入</div>
              <div class="text-2xl font-bold text-blue-600 dark:text-blue-300">
                ¥{{ formatNumber(overviewCards[0].value) }}
              </div>
              <div class="mt-2 text-sm flex items-center">
                <span
                  :class="
                    overviewCards[0].trend >= 0
                      ? 'text-green-600 dark:text-green-400'
                      : 'text-red-600 dark:text-red-400'
                  "
                  class="flex items-center"
                >
                  <icon-up v-if="overviewCards[0].trend >= 0" />
                  <icon-down v-else />
                  {{ Math.abs(overviewCards[0].trend) }}%
                </span>
                <span class="ml-1 text-gray-500 dark:text-gray-400"
                  >较上期</span
                >
              </div>
            </div>
            <div class="stat-icon revenue-icon">
              <icon-money-circle />
            </div>
          </div>
          <div class="stat-footer">
            <div
              class="flex justify-between text-sm text-gray-500 dark:text-gray-400 mt-4"
            >
              <span>日均收入</span>
              <span class="font-medium text-blue-600 dark:text-blue-300">
                ¥{{ formatNumber(overviewCards[0].value / 30) }}
              </span>
            </div>
          </div>
        </a-card>

        <!-- 订单数量 -->
        <a-card class="stat-card orders-card" :loading="loading">
          <div class="flex items-center justify-between">
            <div>
              <div class="text-gray-500 dark:text-gray-300 mb-2">订单数量</div>
              <div
                class="text-2xl font-bold text-green-600 dark:text-green-300"
              >
                {{ formatNumber(overviewCards[1].value) }}
              </div>
              <div class="mt-2 text-sm flex items-center">
                <span
                  :class="
                    overviewCards[1].trend >= 0
                      ? 'text-green-600 dark:text-green-400'
                      : 'text-red-600 dark:text-red-400'
                  "
                  class="flex items-center"
                >
                  <icon-up v-if="overviewCards[1].trend >= 0" />
                  <icon-down v-else />
                  {{ Math.abs(overviewCards[1].trend) }}%
                </span>
                <span class="ml-1 text-gray-500 dark:text-gray-400"
                  >较上期</span
                >
              </div>
            </div>
            <div class="stat-icon orders-icon">
              <icon-file />
            </div>
          </div>
          <div class="stat-footer">
            <div
              class="flex justify-between text-sm text-gray-500 dark:text-gray-400 mt-4"
            >
              <span>完成率</span>
              <span class="font-medium text-green-600 dark:text-green-300">
                95%
              </span>
            </div>
          </div>
        </a-card>

        <!-- 访问量 -->
        <a-card class="stat-card visits-card" :loading="loading">
          <div class="flex items-center justify-between">
            <div>
              <div class="text-gray-500 dark:text-gray-300 mb-2">访问量</div>
              <div
                class="text-2xl font-bold text-purple-600 dark:text-purple-300"
              >
                {{ formatNumber(overviewCards[2].value) }}
              </div>
              <div class="mt-2 text-sm flex items-center">
                <span
                  :class="
                    overviewCards[2].trend >= 0
                      ? 'text-green-600 dark:text-green-400'
                      : 'text-red-600 dark:text-red-400'
                  "
                  class="flex items-center"
                >
                  <icon-up v-if="overviewCards[2].trend >= 0" />
                  <icon-down v-else />
                  {{ Math.abs(overviewCards[2].trend) }}%
                </span>
                <span class="ml-1 text-gray-500 dark:text-gray-400"
                  >较上期</span
                >
              </div>
            </div>
            <div class="stat-icon visits-icon">
              <icon-eye />
            </div>
          </div>
          <div class="stat-footer">
            <div
              class="flex justify-between text-sm text-gray-500 dark:text-gray-400 mt-4"
            >
              <span>转化率</span>
              <span class="font-medium text-purple-600 dark:text-purple-300">
                15%
              </span>
            </div>
          </div>
        </a-card>

        <!-- 新增用户 -->
        <a-card class="stat-card users-card" :loading="loading">
          <div class="flex items-center justify-between">
            <div>
              <div class="text-gray-500 dark:text-gray-300 mb-2">新增用户</div>
              <div
                class="text-2xl font-bold text-orange-600 dark:text-orange-300"
              >
                {{ formatNumber(overviewCards[3].value) }}
              </div>
              <div class="mt-2 text-sm flex items-center">
                <span
                  :class="
                    overviewCards[3].trend >= 0
                      ? 'text-green-600 dark:text-green-400'
                      : 'text-red-600 dark:text-red-400'
                  "
                  class="flex items-center"
                >
                  <icon-up v-if="overviewCards[3].trend >= 0" />
                  <icon-down v-else />
                  {{ Math.abs(overviewCards[3].trend) }}%
                </span>
                <span class="ml-1 text-gray-500 dark:text-gray-400"
                  >较上期</span
                >
              </div>
            </div>
            <div class="stat-icon members-icon">
              <icon-user-group />
            </div>
          </div>
          <div class="stat-footer">
            <div
              class="flex justify-between text-sm text-gray-500 dark:text-gray-400 mt-4"
            >
              <span>用户总数</span>
              <span class="font-medium text-orange-600 dark:text-orange-300">
                {{ formatNumber(478) }}
              </span>
            </div>
          </div>
        </a-card>
      </div>
    </div>

    <!-- 图表区域 -->
    <a-row :gutter="16" class="mb-4">
      <!-- 销售趋势图表 -->
      <a-col :span="16">
        <a-card class="chart-card" title="销售趋势" :loading="loading">
          <template #extra>
            <a-space>
              <a-radio-group type="button" v-model="timeRange" size="small">
                <a-radio value="today">今日</a-radio>
                <a-radio value="week">本周</a-radio>
                <a-radio value="month">本月</a-radio>
                <a-radio value="year">本年</a-radio>
              </a-radio-group>
              <a-button type="text" size="small">
                <template #icon><icon-download /></template>
                导出数据
              </a-button>
            </a-space>
          </template>
          <div ref="salesChartRef" class="chart-container"></div>
        </a-card>
      </a-col>

      <!-- 商品销量排行 -->
      <a-col :span="8">
        <a-card class="rank-card" title="商品销量排行" :loading="loading">
          <template #extra>
            <a-select v-model="rankTimeRange" size="small" style="width: 100px">
              <a-option value="day">今日</a-option>
              <a-option value="week">本周</a-option>
              <a-option value="month">本月</a-option>
            </a-select>
          </template>
          <div class="rank-list">
            <div
              v-for="(item, index) in productRanking"
              :key="item.id"
              class="rank-item"
            >
              <span class="rank-number" :class="'rank-' + (index + 1)">{{
                index + 1
              }}</span>
              <span class="rank-info">
                <span class="rank-name">{{ item.name }}</span>
                <span class="rank-category">{{ item.category }}</span>
              </span>
              <span class="rank-value">{{ formatNumber(item.sales) }}件</span>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 下半部分数据 -->
    <a-row :gutter="16">
      <!-- 左侧图表区域 -->
      <a-col :span="16">
        <a-row :gutter="[16, 16]">
          <!-- 商品类别分布 -->
          <a-col :span="12">
            <a-card class="chart-card" title="商品类别分布" :loading="loading">
              <template #extra>
                <a-select
                  v-model="categoryTimeRange"
                  size="small"
                  style="width: 100px"
                >
                  <a-option value="week">本周</a-option>
                  <a-option value="month">本月</a-option>
                  <a-option value="year">本年</a-option>
                </a-select>
              </template>
              <div ref="categoryChartRef" class="chart-container"></div>
            </a-card>
          </a-col>

          <!-- 商户运营指标五角图 -->
          <a-col :span="12">
            <a-card class="chart-card" title="商户运营指标" :loading="loading">
              <div ref="businessIndicatorRef" class="chart-container"></div>
            </a-card>
          </a-col>

          <!-- 销售地区分析 - 占据整行 -->
          <a-col :span="24">
            <a-card
              class="chart-card map-chart-card"
              title="销售地区分析"
              :loading="loading"
            >
              <template #extra>
                <div class="flex items-center">
                  <a-select
                    v-model="regionTimeRange"
                    size="small"
                    style="width: 100px; margin-right: 10px"
                  >
                    <a-option value="week">本周</a-option>
                    <a-option value="month">本月</a-option>
                    <a-option value="year">本年</a-option>
                  </a-select>
                  <a-radio-group type="button" v-model="mapType" size="small">
                    <a-radio value="china">全国</a-radio>
                    <a-radio value="guangxi">广西</a-radio>
                  </a-radio-group>
                </div>
              </template>
              <div
                ref="regionChartRef"
                class="chart-container map-container"
              ></div>
            </a-card>
          </a-col>

          <!-- 用户分析 -->
          <a-col :span="12">
            <a-card class="chart-card" title="用户分析" :loading="loading">
              <template #extra>
                <a-tabs type="text" v-model="userAnalysisTab">
                  <a-tab-pane key="age" title="年龄分布"></a-tab-pane>
                  <a-tab-pane key="gender" title="性别比例"></a-tab-pane>
                </a-tabs>
              </template>
              <div ref="userChartRef" class="chart-container"></div>
            </a-card>
          </a-col>

          <!-- 订单趋势 -->
          <a-col :span="12">
            <a-card class="chart-card" title="订单趋势" :loading="loading">
              <template #extra>
                <a-select
                  v-model="orderTrendTimeRange"
                  size="small"
                  style="width: 100px"
                >
                  <a-option value="week">本周</a-option>
                  <a-option value="month">本月</a-option>
                  <a-option value="year">本年</a-option>
                </a-select>
              </template>
              <div ref="orderChartRef" class="chart-container"></div>
            </a-card>
          </a-col>
        </a-row>
      </a-col>

      <!-- 右侧统计区域 -->
      <a-col :span="8">
        <!-- 订单统计 -->
        <a-card class="stats-card" title="订单统计" :loading="loading">
          <template #extra>
            <a-button type="text" size="small" @click="refreshOrderStats">
              <template #icon><icon-refresh /></template>
              刷新
            </a-button>
          </template>
          <div class="order-stats-vertical">
            <div
              v-for="item in orderStats"
              :key="item.type"
              class="stat-item"
              :class="{
                'animate__animated animate__fadeInRight': showAnimation,
              }"
            >
              <div class="stat-header">
                <span class="stat-label">{{ item.label }}</span>
                <a-tag :color="getStatColor(item.type)">{{
                  getStatStatus(item.type)
                }}</a-tag>
              </div>
              <div class="stat-value">
                {{ Math.floor(item.value).toLocaleString() }}
              </div>
              <div class="stat-chart">
                <div
                  class="progress-bar"
                  :style="{ width: getStatProgress(item) + '%' }"
                ></div>
              </div>
            </div>
          </div>
        </a-card>

        <!-- 待办事项 -->
        <a-card class="todo-card mt-4" title="待办事项" :loading="loading">
          <template #extra>
            <a-button type="text" size="small">
              <template #icon><icon-right /></template>
              查看全部
            </a-button>
          </template>
          <div class="todo-list">
            <div
              v-for="todo in todoList"
              :key="todo.type"
              class="todo-item"
              @click="handleTodoClick(todo)"
            >
              <a-badge :color="todo.color" :text="todo.text" />
              <span class="todo-count">{{ todo.count }}</span>
              <icon-right class="todo-arrow" />
            </div>
          </div>
        </a-card>

        <!-- AI智能分析 -->
        <a-card class="ai-card mt-4" title="AI智能分析" :loading="loading">
          <template #extra>
            <a-button
              type="primary"
              size="small"
              :loading="aiAnalysisLoading"
              @click="generateAIAnalysis"
            >
              生成分析
            </a-button>
          </template>
          <div class="ai-analysis-content">
            <div
              v-if="aiAnalysisResult"
              class="bg-gray-50 dark:bg-gray-800 rounded-lg p-3"
            >
              <div class="text-sm text-gray-500 mb-2">
                分析时间: {{ aiAnalysisTime }}
              </div>
              <p
                class="whitespace-pre-line text-gray-700 dark:text-gray-300 text-sm"
              >
                {{ aiAnalysisResult }}
              </p>
            </div>
            <div
              v-else
              class="flex flex-col items-center justify-center py-6 text-gray-400"
            >
              <icon-info-circle :size="24" />
              <p class="mt-2">暂无AI分析记录，点击"生成分析"按钮开始智能分析</p>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, onUnmounted, computed } from "vue";
import { useRouter } from "vue-router";
import * as echarts from "echarts";
import { useTransition } from "@vueuse/core";
import "animate.css";
import {
  IconInfoCircle,
  IconUp,
  IconDown,
  IconDownload,
  IconRefresh,
  IconRight,
  IconSearch,
  IconCompass,
  IconPrinter,
  IconStar,
  IconMoneyCircle,
  IconFile,
  IconEye,
  IconUserGroup,
} from "@arco-design/web-vue/es/icon";
import { ChatLineRound, Connection, Timer } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";

const router = useRouter();
const loading = ref(true);
const timeRange = ref("week");
const rankTimeRange = ref("week");
const userAnalysisTab = ref("age");
const salesChartRef = ref(null);
const orderChartRef = ref(null);
const userChartRef = ref(null);
const categoryTimeRange = ref("week");
const regionTimeRange = ref("week");
const orderTrendTimeRange = ref("week");
const categoryChartRef = ref(null);
const regionChartRef = ref(null);
const mapType = ref("guangxi"); // 默认显示广西地图
let salesChart = null;
let orderChart = null;
let userChart = null;
let categoryChart = null;
let regionChart = null;

const showAnimation = ref(false);
const aiAnalysisLoading = ref(false);
const aiAnalysisResult = ref(null);
const aiAnalysisTime = ref(null);

// 数据概览卡片数据
const overviewCards = ref([
  {
    title: "今日销售额",
    value: 12580.5,
    prefix: "¥",
    unit: "",
    trend: 12.5,
    tooltip: "今日已完成订单的总销售金额",
  },
  {
    title: "今日订单数",
    value: 258,
    prefix: "",
    unit: "单",
    trend: 8.2,
    tooltip: "今日新增的订单总数",
  },
  {
    title: "访客数",
    value: 1234,
    prefix: "",
    unit: "人",
    trend: -5.8,
    tooltip: "今日店铺访问的独立访客数",
  },
  {
    title: "转化率",
    value: 15.8,
    prefix: "",
    unit: "%",
    trend: 2.1,
    tooltip: "访客转化为订单的比率",
  },
]);

// 商品销量排行数据
const productRanking = ref([
  { id: 1, name: "特色桂花糕", category: "特色小吃", sales: 328 },
  { id: 2, name: "贵港荔枝", category: "水果生鲜", sales: 286 },
  { id: 3, name: "手工艺品", category: "文创用品", sales: 256 },
  { id: 4, name: "特产组合礼盒", category: "伴手礼", sales: 198 },
  { id: 5, name: "贵港特色小吃套装", sales: 176, trend: 15.6 },
]);

// 订单统计数据
const orderStats = ref([
  { type: "total", label: "总订单数", value: 1580 },
  { type: "pending", label: "待处理", value: 32 },
  { type: "processing", label: "处理中", value: 58 },
  { type: "completed", label: "已完成", value: 1490 },
]);

// 待办事项数据
const todoList = ref([
  {
    type: "pending_payment",
    text: "待付款订单",
    count: 12,
    color: "#165DFF",
    route: "/merchant/orders?status=pending_payment",
  },
  {
    type: "pending_delivery",
    text: "待发货订单",
    count: 8,
    color: "#00B42A",
    route: "/merchant/orders?status=pending_delivery",
  },
  {
    type: "pending_receipt",
    text: "待收货订单",
    count: 24,
    color: "#F7BA1E",
    route: "/merchant/orders?status=pending_receipt",
  },
  {
    type: "pending_review",
    text: "待评价订单",
    count: 36,
    color: "#FF7D00",
    route: "/merchant/orders?status=pending_review",
  },
  {
    type: "after_sales",
    text: "售后/退款",
    count: 5,
    color: "#F53F3F",
    route: "/merchant/orders?status=after_sales",
  },
]);

// 格式化数字
const formatNumber = (num) => {
  return num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, "$1,");
};

// 为每个统计数字创建过渡效果
const transitionedValues = computed(() => {
  const result = {};
  orderStats.value.forEach((item) => {
    const source = ref(item.value);
    result[item.type] = useTransition(source);
  });
  return result;
});

// 获取统计项状态颜色
const getStatColor = (type) => {
  const colors = {
    total: "blue",
    pending: "orange",
    processing: "green",
    completed: "purple",
  };
  return colors[type] || "blue";
};

// 获取统计项状态文本
const getStatStatus = (type) => {
  const status = {
    total: "总计",
    pending: "待处理",
    processing: "处理中",
    completed: "已完成",
  };
  return status[type] || "";
};

// 获取进度条百分比
const getStatProgress = (item) => {
  const total =
    orderStats.value.find((stat) => stat.type === "total")?.value || 1;
  return (item.value / total) * 100;
};

// 初始化销售趋势图表
const initSalesChart = () => {
  if (!salesChartRef.value) return;
  salesChart = echarts.init(salesChartRef.value);

  // 根据时间范围获取不同的数据
  const getDataByTimeRange = () => {
    const dataMap = {
      today: {
        xAxis: [
          "00:00",
          "03:00",
          "06:00",
          "09:00",
          "12:00",
          "15:00",
          "18:00",
          "21:00",
        ],
        sales: [1200, 1320, 1500, 2800, 3500, 3200, 2500, 1800],
        orders: [120, 132, 150, 280, 350, 320, 250, 180],
      },
      week: {
        xAxis: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
        sales: [4200, 5800, 6300, 5200, 6800, 8500, 9200],
        orders: [420, 580, 630, 520, 680, 850, 920],
      },
      month: {
        xAxis: ["1日", "5日", "10日", "15日", "20日", "25日", "30日"],
        sales: [12500, 15800, 18600, 16200, 19800, 22500, 25200],
        orders: [1250, 1580, 1860, 1620, 1980, 2250, 2520],
      },
      year: {
        xAxis: [
          "1月",
          "2月",
          "3月",
          "4月",
          "5月",
          "6月",
          "7月",
          "8月",
          "9月",
          "10月",
          "11月",
          "12月",
        ],
        sales: [
          35000, 28000, 42000, 48000, 52000, 56000, 62000, 68000, 72000, 76000,
          82000, 91000,
        ],
        orders: [
          3500, 2800, 4200, 4800, 5200, 5600, 6200, 6800, 7200, 7600, 8200,
          9100,
        ],
      },
    };
    return dataMap[timeRange.value] || dataMap.week;
  };

  const data = getDataByTimeRange();

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        crossStyle: {
          color: "#999",
        },
        lineStyle: {
          type: "dashed",
        },
      },
      backgroundColor: "rgba(255, 255, 255, 0.9)",
      borderColor: "#f2f3f5",
      borderWidth: 1,
      textStyle: {
        color: "#1d2129",
      },
      formatter: function (params) {
        let result = params[0].axisValue + "<br/>";
        params.forEach((item) => {
          if (item.seriesName === "销售额") {
            result += `${item.marker} ${item.seriesName}: ¥${item.value.toLocaleString()}<br/>`;
          } else {
            result += `${item.marker} ${item.seriesName}: ${item.value}单<br/>`;
          }
        });
        return result;
      },
    },
    legend: {
      data: ["销售额", "订单量"],
      right: 10,
      top: 0,
      textStyle: {
        color: "#4e5969",
      },
      itemWidth: 12,
      itemHeight: 12,
      itemGap: 24,
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: data.xAxis,
      axisLine: {
        lineStyle: {
          color: "#E5E6EB",
          width: 1,
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#4e5969",
        fontSize: 12,
        margin: 12,
      },
    },
    yAxis: [
      {
        type: "value",
        name: "销售额",
        min: 0,
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          lineStyle: {
            type: "dashed",
            color: "#E5E6EB",
            width: 1,
          },
        },
        axisLabel: {
          color: "#4e5969",
          fontSize: 12,
          formatter: "¥{value}",
        },
      },
      {
        type: "value",
        name: "订单量",
        min: 0,
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          show: false,
        },
        axisLabel: {
          color: "#4e5969",
          fontSize: 12,
          formatter: "{value}单",
        },
      },
    ],
    series: [
      {
        name: "销售额",
        type: "bar",
        barWidth: "20%",
        data: data.sales,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "rgba(22, 93, 255, 0.85)" },
            { offset: 1, color: "rgba(22, 93, 255, 0.3)" },
          ]),
          borderRadius: [4, 4, 0, 0],
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "rgba(22, 93, 255, 1)" },
              { offset: 1, color: "rgba(22, 93, 255, 0.5)" },
            ]),
          },
        },
      },
      {
        name: "订单量",
        type: "line",
        smooth: true,
        symbol: "circle",
        symbolSize: 8,
        yAxisIndex: 1,
        data: data.orders,
        itemStyle: {
          color: "#722ED1",
        },
        lineStyle: {
          width: 3,
          shadowColor: "rgba(114, 46, 209, 0.3)",
          shadowBlur: 10,
          shadowOffsetY: 6,
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "rgba(114, 46, 209, 0.3)" },
            { offset: 1, color: "rgba(114, 46, 209, 0.05)" },
          ]),
        },
      },
    ],
  };

  salesChart.setOption(option);
};

// 初始化订单趋势图表
const initOrderChart = () => {
  if (!orderChartRef.value) return;
  orderChart = echarts.init(orderChartRef.value);

  // 根据时间范围获取不同的数据
  const getDataByTimeRange = () => {
    const dataMap = {
      week: {
        xAxis: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
        newOrders: [32, 45, 53, 42, 58, 68, 75],
        completedOrders: [28, 40, 48, 38, 52, 60, 68],
        cancelledOrders: [4, 5, 5, 4, 6, 8, 7],
      },
      month: {
        xAxis: ["第1周", "第2周", "第3周", "第4周"],
        newOrders: [180, 220, 260, 290],
        completedOrders: [160, 195, 230, 260],
        cancelledOrders: [20, 25, 30, 30],
      },
      year: {
        xAxis: [
          "1月",
          "2月",
          "3月",
          "4月",
          "5月",
          "6月",
          "7月",
          "8月",
          "9月",
          "10月",
          "11月",
          "12月",
        ],
        newOrders: [350, 280, 420, 480, 520, 560, 620, 680, 720, 760, 820, 910],
        completedOrders: [
          320, 250, 380, 430, 470, 510, 570, 620, 660, 700, 750, 840,
        ],
        cancelledOrders: [30, 30, 40, 50, 50, 50, 50, 60, 60, 60, 70, 70],
      },
    };
    return dataMap[orderTrendTimeRange.value] || dataMap.week;
  };

  const data = getDataByTimeRange();

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
        shadowStyle: {
          color: "rgba(0, 0, 0, 0.05)",
        },
      },
      backgroundColor: "rgba(255, 255, 255, 0.9)",
      borderColor: "#f2f3f5",
      borderWidth: 1,
      textStyle: {
        color: "#1d2129",
      },
      formatter: function (params) {
        let result = params[0].axisValue + "<br/>";
        params.forEach((item) => {
          result += `${item.marker} ${item.seriesName}: ${item.value}单<br/>`;
        });
        return result;
      },
    },
    legend: {
      data: ["新增订单", "已完成", "已取消"],
      bottom: "0%",
      left: "center",
      itemWidth: 10,
      itemHeight: 10,
      textStyle: {
        color: "#4e5969",
      },
      itemGap: 20,
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "15%",
      top: "8%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: data.xAxis,
      axisLine: {
        lineStyle: {
          color: "#E5E6EB",
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#4e5969",
        fontSize: 12,
        margin: 12,
      },
    },
    yAxis: {
      type: "value",
      name: "订单数",
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      splitLine: {
        lineStyle: {
          type: "dashed",
          color: "#E5E6EB",
        },
      },
      axisLabel: {
        color: "#4e5969",
        fontSize: 12,
        formatter: "{value}单",
      },
    },
    series: [
      {
        name: "新增订单",
        type: "bar",
        stack: "订单",
        emphasis: {
          focus: "series",
        },
        data: data.newOrders,
        barWidth: "30%",
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "rgba(22, 93, 255, 0.9)" },
            { offset: 1, color: "rgba(22, 93, 255, 0.4)" },
          ]),
          borderRadius: [4, 4, 0, 0],
        },
      },
      {
        name: "已完成",
        type: "bar",
        stack: "订单",
        emphasis: {
          focus: "series",
        },
        data: data.completedOrders,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "rgba(0, 180, 42, 0.9)" },
            { offset: 1, color: "rgba(0, 180, 42, 0.4)" },
          ]),
        },
      },
      {
        name: "已取消",
        type: "bar",
        stack: "订单",
        emphasis: {
          focus: "series",
        },
        data: data.cancelledOrders,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "rgba(245, 63, 63, 0.9)" },
            { offset: 1, color: "rgba(245, 63, 63, 0.4)" },
          ]),
        },
      },
      {
        name: "订单趋势",
        type: "line",
        smooth: true,
        symbol: "emptyCircle",
        symbolSize: 6,
        showSymbol: false,
        lineStyle: {
          width: 2,
          color: "#722ED1",
        },
        emphasis: {
          focus: "series",
          lineStyle: {
            width: 3,
          },
        },
        data: data.newOrders,
      },
    ],
  };

  orderChart.setOption(option);
};

// 初始化用户分析图表
const initUserChart = () => {
  if (!userChartRef.value) return;
  userChart = echarts.init(userChartRef.value);

  const options = {
    age: {
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
        backgroundColor: "rgba(255, 255, 255, 0.9)",
        borderColor: "#f2f3f5",
        borderWidth: 1,
        textStyle: {
          color: "#1d2129",
        },
        formatter: function (params) {
          return `${params[0].name}<br/>${params[0].marker} ${params[0].seriesName}: ${params[0].value}人`;
        },
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "3%",
        containLabel: true,
      },
      xAxis: {
        type: "value",
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          lineStyle: {
            type: "dashed",
            color: "#E5E6EB",
          },
        },
        axisLabel: {
          color: "#4e5969",
          fontSize: 12,
        },
      },
      yAxis: {
        type: "category",
        data: ["18-24岁", "25-34岁", "35-44岁", "45-54岁", "55岁以上"],
        axisLine: {
          lineStyle: {
            color: "#E5E6EB",
          },
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          color: "#4e5969",
          fontSize: 12,
        },
      },
      series: [
        {
          name: "用户数量",
          type: "bar",
          data: [320, 580, 420, 250, 180],
          barWidth: "40%",
          itemStyle: {
            color: function (params) {
              // 自定义颜色渐变
              const colorList = [
                new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  { offset: 0, color: "rgba(22, 93, 255, 0.9)" },
                  { offset: 1, color: "rgba(22, 93, 255, 0.4)" },
                ]),
                new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  { offset: 0, color: "rgba(114, 46, 209, 0.9)" },
                  { offset: 1, color: "rgba(114, 46, 209, 0.4)" },
                ]),
                new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  { offset: 0, color: "rgba(0, 180, 42, 0.9)" },
                  { offset: 1, color: "rgba(0, 180, 42, 0.4)" },
                ]),
                new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  { offset: 0, color: "rgba(255, 125, 0, 0.9)" },
                  { offset: 1, color: "rgba(255, 125, 0, 0.4)" },
                ]),
                new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  { offset: 0, color: "rgba(245, 63, 63, 0.9)" },
                  { offset: 1, color: "rgba(245, 63, 63, 0.4)" },
                ]),
              ];
              return colorList[params.dataIndex];
            },
            borderRadius: [0, 4, 4, 0],
          },
          label: {
            show: true,
            position: "right",
            formatter: "{c}人",
            color: "#1d2129",
          },
        },
      ],
    },
    gender: {
      tooltip: {
        trigger: "item",
        backgroundColor: "rgba(255, 255, 255, 0.9)",
        borderColor: "#f2f3f5",
        borderWidth: 1,
        textStyle: {
          color: "#1d2129",
        },
        formatter: function (params) {
          return `${params.name}<br/>${params.marker} ${params.seriesName}: ${params.value}人 (${params.percent}%)`;
        },
      },
      legend: {
        bottom: "0%",
        left: "center",
        itemWidth: 10,
        itemHeight: 10,
        textStyle: {
          color: "#4e5969",
        },
        icon: "circle",
      },
      series: [
        {
          name: "性别比例",
          type: "pie",
          radius: ["40%", "70%"],
          center: ["50%", "40%"],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 6,
            borderColor: "#fff",
            borderWidth: 2,
          },
          label: {
            show: false,
            position: "center",
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: "bold",
              formatter: "{b}\n{c}人\n{d}%",
            },
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.2)",
            },
          },
          labelLine: {
            show: false,
          },
          data: [
            {
              value: 580,
              name: "女性",
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: "#FF7D00" },
                  { offset: 1, color: "#FFCF9D" },
                ]),
              },
            },
            {
              value: 420,
              name: "男性",
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: "#165DFF" },
                  { offset: 1, color: "#9CB4FF" },
                ]),
              },
            },
          ],
        },
      ],
    },
  };

  userChart.setOption(options[userAnalysisTab.value]);
};

// 监听用户分析标签页变化
watch(userAnalysisTab, (newValue) => {
  nextTick(() => {
    initUserChart();
  });
});

// 监听时间范围变化
watch(timeRange, (newValue) => {
  // 根据时间范围重新渲染图表
  nextTick(() => {
    initSalesChart();
  });
});

// 监听订单趋势时间范围变化
watch(orderTrendTimeRange, (newValue) => {
  nextTick(() => {
    initOrderChart();
  });
});

// 处理待办事项点击
const handleTodoClick = (todo) => {
  router.push(todo.route);
};

// 刷新订单统计
const refreshOrderStats = async () => {
  loading.value = true;
  showAnimation.value = false;

  // 模拟数据刷新
  await new Promise((resolve) => setTimeout(resolve, 1000));

  // 更新数据
  orderStats.value = [
    { type: "total", label: "总订单数", value: 1580 },
    { type: "pending", label: "待处理", value: 32 },
    { type: "processing", label: "处理中", value: 58 },
    { type: "completed", label: "已完成", value: 1490 },
  ];

  loading.value = false;
  showAnimation.value = true;
};

// 初始化商品类别分布图表
const initCategoryChart = () => {
  if (!categoryChartRef.value) return;
  categoryChart = echarts.init(categoryChartRef.value);

  // 根据时间范围获取不同的数据
  const getDataByTimeRange = () => {
    const dataMap = {
      week: [
        { value: 335, name: "特色小吃", percentage: 28.5 },
        { value: 310, name: "水果生鲜", percentage: 26.3 },
        { value: 234, name: "文创用品", percentage: 19.9 },
        { value: 154, name: "伴手礼", percentage: 13.1 },
        { value: 147, name: "其他", percentage: 12.2 },
      ],
      month: [
        { value: 1235, name: "特色小吃", percentage: 30.2 },
        { value: 1010, name: "水果生鲜", percentage: 24.7 },
        { value: 834, name: "文创用品", percentage: 20.4 },
        { value: 554, name: "伴手礼", percentage: 13.5 },
        { value: 447, name: "其他", percentage: 11.2 },
      ],
      year: [
        { value: 12335, name: "特色小吃", percentage: 32.5 },
        { value: 9010, name: "水果生鲜", percentage: 23.8 },
        { value: 7834, name: "文创用品", percentage: 20.7 },
        { value: 5154, name: "伴手礼", percentage: 13.6 },
        { value: 3547, name: "其他", percentage: 9.4 },
      ],
    };
    return dataMap[categoryTimeRange.value] || dataMap.week;
  };

  const data = getDataByTimeRange();

  // 自定义颜色
  const colors = [
    new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      { offset: 0, color: "#165DFF" },
      { offset: 1, color: "#7B9EFF" },
    ]),
    new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      { offset: 0, color: "#00B42A" },
      { offset: 1, color: "#7BE188" },
    ]),
    new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      { offset: 0, color: "#F7BA1E" },
      { offset: 1, color: "#FBDC8E" },
    ]),
    new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      { offset: 0, color: "#722ED1" },
      { offset: 1, color: "#B490E0" },
    ]),
    new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      { offset: 0, color: "#FF7D00" },
      { offset: 1, color: "#FFBB7D" },
    ]),
  ];

  const option = {
    tooltip: {
      trigger: "item",
      formatter: function (params) {
        return `${params.name}<br/>${params.marker} 销售额: ${params.value.toLocaleString()}元<br/>${params.marker} 占比: ${params.percent}%`;
      },
      backgroundColor: "rgba(255, 255, 255, 0.9)",
      borderColor: "#f2f3f5",
      borderWidth: 1,
      textStyle: {
        color: "#1d2129",
      },
    },
    legend: {
      orient: "vertical",
      right: 10,
      top: "center",
      itemWidth: 10,
      itemHeight: 10,
      icon: "circle",
      textStyle: {
        color: "#4e5969",
        fontSize: 12,
      },
      formatter: function (name) {
        const item = data.find((item) => item.name === name);
        return `${name} ${item.percentage}%`;
      },
    },
    series: [
      {
        name: "商品类别",
        type: "pie",
        radius: ["50%", "70%"],
        center: ["35%", "50%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: false,
        },
        emphasis: {
          label: {
            show: true,
            formatter: "{b}\n{d}%",
            fontSize: 14,
            fontWeight: "bold",
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.2)",
          },
        },
        labelLine: {
          show: false,
        },
        data: data.map((item, index) => {
          return {
            value: item.value,
            name: item.name,
            itemStyle: {
              color: colors[index % colors.length],
            },
          };
        }),
      },
    ],
  };

  categoryChart.setOption(option);
};

// 监听商品类别时间范围变化
watch(categoryTimeRange, (newValue) => {
  nextTick(() => {
    initCategoryChart();
  });
});

// 初始化销售地区分析图表
const initRegionChart = () => {
  if (!regionChartRef.value) return;
  regionChart = echarts.init(regionChartRef.value);

  // 根据地图类型和时间范围获取不同的数据
  const getDataByMapTypeAndTime = () => {
    // 全国主要省份数据
    const chinaDataMap = {
      week: [
        { name: "广西壮族自治区", value: 21200, percentage: 28.5 },
        { name: "广东省", value: 18600, percentage: 25.0 },
        { name: "北京市", value: 12500, percentage: 16.8 },
        { name: "上海市", value: 10800, percentage: 14.5 },
        { name: "浙江省", value: 8900, percentage: 12.0 },
        { name: "江苏省", value: 2400, percentage: 3.2 },
        // 添加更多省份数据，确保全国地图有数据展示
        { name: "山东省", value: 7800, percentage: 10.5 },
        { name: "四川省", value: 6500, percentage: 8.7 },
        { name: "河南省", value: 5900, percentage: 7.9 },
        { name: "湖北省", value: 5400, percentage: 7.2 },
        { name: "湖南省", value: 4800, percentage: 6.4 },
        { name: "河北省", value: 4200, percentage: 5.6 },
        { name: "福建省", value: 3900, percentage: 5.2 },
        { name: "陕西省", value: 3600, percentage: 4.8 },
        { name: "辽宁省", value: 3400, percentage: 4.5 },
        { name: "江西省", value: 3200, percentage: 4.3 },
        { name: "黑龙江省", value: 2900, percentage: 3.9 },
        { name: "吉林省", value: 2700, percentage: 3.6 },
        { name: "安徽省", value: 3800, percentage: 5.1 },
        { name: "海南省", value: 2500, percentage: 3.3 },
        { name: "贵州省", value: 2200, percentage: 2.9 },
        { name: "云南省", value: 2800, percentage: 3.7 },
        { name: "重庆市", value: 3300, percentage: 4.4 },
        { name: "天津市", value: 2600, percentage: 3.5 },
        { name: "内蒙古自治区", value: 2100, percentage: 2.8 },
        { name: "山西省", value: 1900, percentage: 2.5 },
        { name: "广西壮族自治区", value: 3100, percentage: 4.1 },
        { name: "甘肃省", value: 1700, percentage: 2.3 },
        { name: "青海省", value: 1200, percentage: 1.6 },
        { name: "宁夏回族自治区", value: 1000, percentage: 1.3 },
        { name: "新疆维吾尔自治区", value: 1800, percentage: 2.4 },
        { name: "西藏自治区", value: 800, percentage: 1.1 },
        { name: "台湾省", value: 3500, percentage: 4.7 },
      ],
      month: [
        // 月度数据也需要为全部省份添加数据
        { name: "广西壮族自治区", value: 82000, percentage: 29.2 },
        { name: "广东省", value: 68000, percentage: 24.2 },
        { name: "北京市", value: 45000, percentage: 16.0 },
        { name: "上海市", value: 38000, percentage: 13.5 },
        { name: "浙江省", value: 32000, percentage: 11.4 },
        { name: "江苏省", value: 16000, percentage: 5.7 },
        // 添加其他省份的月度数据...
        { name: "山东省", value: 28000, percentage: 9.9 },
        { name: "四川省", value: 23000, percentage: 8.2 },
        { name: "河南省", value: 21000, percentage: 7.5 },
        { name: "湖北省", value: 19000, percentage: 6.8 },
        { name: "湖南省", value: 17000, percentage: 6.0 },
        { name: "河北省", value: 15000, percentage: 5.3 },
        { name: "福建省", value: 14000, percentage: 5.0 },
        { name: "陕西省", value: 13000, percentage: 4.6 },
        { name: "辽宁省", value: 12000, percentage: 4.3 },
        { name: "江西省", value: 11000, percentage: 3.9 },
        { name: "黑龙江省", value: 10000, percentage: 3.6 },
        { name: "吉林省", value: 9500, percentage: 3.4 },
        { name: "安徽省", value: 14500, percentage: 5.2 },
        { name: "海南省", value: 9000, percentage: 3.2 },
        { name: "贵州省", value: 8000, percentage: 2.8 },
        { name: "云南省", value: 10500, percentage: 3.7 },
        { name: "重庆市", value: 12500, percentage: 4.4 },
        { name: "天津市", value: 9500, percentage: 3.4 },
        { name: "内蒙古自治区", value: 7500, percentage: 2.7 },
        { name: "山西省", value: 7000, percentage: 2.5 },
        { name: "广西壮族自治区", value: 11500, percentage: 4.1 },
        { name: "甘肃省", value: 6500, percentage: 2.3 },
        { name: "青海省", value: 4500, percentage: 1.6 },
        { name: "宁夏回族自治区", value: 3800, percentage: 1.4 },
        { name: "新疆维吾尔自治区", value: 6800, percentage: 2.4 },
        { name: "西藏自治区", value: 3000, percentage: 1.1 },
        { name: "台湾省", value: 13000, percentage: 4.6 },
      ],
      year: [
        // 年度数据同样需要完整
        { name: "广西壮族自治区", value: 850000, percentage: 30.5 },
        { name: "广东省", value: 720000, percentage: 25.8 },
        { name: "北京市", value: 420000, percentage: 15.1 },
        { name: "上海市", value: 380000, percentage: 13.6 },
        { name: "浙江省", value: 320000, percentage: 11.5 },
        { name: "江苏省", value: 98000, percentage: 3.5 },
        // 添加其他省份的年度数据...
        { name: "山东省", value: 280000, percentage: 10.0 },
        { name: "四川省", value: 230000, percentage: 8.2 },
        { name: "河南省", value: 210000, percentage: 7.5 },
        { name: "湖北省", value: 190000, percentage: 6.8 },
        { name: "湖南省", value: 170000, percentage: 6.1 },
        { name: "河北省", value: 150000, percentage: 5.4 },
        { name: "福建省", value: 140000, percentage: 5.0 },
        { name: "陕西省", value: 130000, percentage: 4.7 },
        { name: "辽宁省", value: 120000, percentage: 4.3 },
        { name: "江西省", value: 110000, percentage: 3.9 },
        { name: "黑龙江省", value: 100000, percentage: 3.6 },
        { name: "吉林省", value: 95000, percentage: 3.4 },
        { name: "安徽省", value: 145000, percentage: 5.2 },
        { name: "海南省", value: 90000, percentage: 3.2 },
        { name: "贵州省", value: 80000, percentage: 2.9 },
        { name: "云南省", value: 105000, percentage: 3.8 },
        { name: "重庆市", value: 125000, percentage: 4.5 },
        { name: "天津市", value: 95000, percentage: 3.4 },
        { name: "内蒙古自治区", value: 75000, percentage: 2.7 },
        { name: "山西省", value: 70000, percentage: 2.5 },
        { name: "广西壮族自治区", value: 115000, percentage: 4.1 },
        { name: "甘肃省", value: 65000, percentage: 2.3 },
        { name: "青海省", value: 45000, percentage: 1.6 },
        { name: "宁夏回族自治区", value: 38000, percentage: 1.4 },
        { name: "新疆维吾尔自治区", value: 68000, percentage: 2.4 },
        { name: "西藏自治区", value: 30000, percentage: 1.1 },
        { name: "台湾省", value: 130000, percentage: 4.7 },
      ],
    };

    // 广西各地市数据 - 保持不变
    const guangxiDataMap = {
      week: [
        { name: "南宁市", value: 8500, percentage: 28.3 },
        { name: "柳州市", value: 6200, percentage: 20.7 },
        { name: "桂林市", value: 5800, percentage: 19.3 },
        { name: "贵港市", value: 4200, percentage: 14.0 },
        { name: "玉林市", value: 3500, percentage: 11.7 },
        { name: "钦州市", value: 1800, percentage: 6.0 },
      ],
      month: [
        { name: "南宁市", value: 32000, percentage: 29.1 },
        { name: "柳州市", value: 22000, percentage: 20.0 },
        { name: "桂林市", value: 20000, percentage: 18.2 },
        { name: "贵港市", value: 16000, percentage: 14.5 },
        { name: "玉林市", value: 12000, percentage: 10.9 },
        { name: "钦州市", value: 8000, percentage: 7.3 },
      ],
      year: [
        { name: "南宁市", value: 320000, percentage: 30.2 },
        { name: "柳州市", value: 210000, percentage: 19.8 },
        { name: "桂林市", value: 195000, percentage: 18.4 },
        { name: "贵港市", value: 150000, percentage: 14.2 },
        { name: "玉林市", value: 120000, percentage: 11.3 },
        { name: "钦州市", value: 65000, percentage: 6.1 },
      ],
    };

    // 根据当前地图类型返回相应数据
    return mapType.value === "china"
      ? chinaDataMap[regionTimeRange.value] || chinaDataMap.week
      : guangxiDataMap[regionTimeRange.value] || guangxiDataMap.week;
  };

  const data = getDataByMapTypeAndTime();

  // 计算最大值和最小值，用于地图颜色渐变
  const values = data.map((item) => item.value);
  const maxValue = Math.max(...values);
  const minValue = Math.min(...values);

  // 地图配置
  const option = {
    title: {
      text: mapType.value === "china" ? "全国销售分布" : "广西销售分布",
      left: "center",
      textStyle: {
        color: "#666",
        fontSize: 16,
        fontWeight: "normal",
      },
    },
    tooltip: {
      trigger: "item",
      formatter: function (params) {
        const item = data.find((d) => d.name === params.name);
        if (item) {
          return `${params.name}<br/>销售额: ${item.value.toLocaleString()}元<br/>占比: ${item.percentage}%`;
        }
        return params.name;
      },
      backgroundColor: "rgba(255, 255, 255, 0.9)",
      borderColor: "#f2f3f5",
      borderWidth: 1,
      textStyle: {
        color: "#1d2129",
      },
    },
    visualMap: {
      type: "continuous",
      min: minValue,
      max: maxValue,
      text: ["高", "低"],
      realtime: false,
      calculable: true,
      inRange: {
        color: ["#C6E5FF", "#409EFF", "#2B7ADF", "#0D5EFF"],
      },
      textStyle: {
        color: "#4e5969",
      },
      left: "left",
      bottom: 10,
      formatter: function (value) {
        if (value >= 10000) {
          return (value / 10000).toFixed(1) + "w";
        } else if (value >= 1000) {
          return (value / 1000).toFixed(1) + "k";
        }
        return value;
      },
    },
    geo: {
      map: mapType.value,
      roam: false, // 禁止缩放和平移
      zoom: mapType.value === "china" ? 1.1 : 1.05, // 中国地图和广西地图的缩放比例分别设置
      label: {
        show: true,
        fontSize: mapType.value === "china" ? 8 : 10, // 全国地图字体小一点
        color: "#333",
      },
      emphasis: {
        label: {
          show: true,
          color: "#fff",
          fontSize: mapType.value === "china" ? 10 : 12,
          fontWeight: "bold",
        },
        itemStyle: {
          areaColor: "#0D5EFF",
          borderWidth: 1,
        },
      },
      itemStyle: {
        borderColor: "#fff",
        borderWidth: 1,
        areaColor: "#f3f4f5",
      },
      // 中国地图配置
      // 设置视图范围，集中显示从黑龙江到海南的主要区域
      layoutCenter: mapType.value === "china" ? ["50%", "65%"] : ["50%", "50%"],
      // 中国地图稍微放大，广西地图居中显示
      layoutSize: mapType.value === "china" ? "115%" : "85%",
      // 禁止选择区域
      selectedMode: false,
    },
    // 系列配置
    series: [
      {
        name: "销售额",
        type: "map",
        geoIndex: 0,
        data: data.map((item) => {
          return {
            name: item.name,
            value: item.value,
          };
        }),
      },
      // 添加省份标签层，直接展示数据
      {
        name: "省份数据标签",
        type: "scatter",
        coordinateSystem: "geo",
        symbol: "pin", // 使用图钉图标
        symbolSize: function (val) {
          // 获取数据名称
          let dataName;
          if (typeof val === "object") {
            // 在回调中可能返回不同结构的val
            dataName =
              val.name || (val[3] ? val[3] : val.data ? val.data.name : null);
          }

          // 根据地图类型和数据值调整标记大小
          if (mapType.value === "china") {
            // 安全地获取数据项
            let percentage = 0;
            if (dataName) {
              const item = data.find((d) => d.name === dataName);
              percentage = item ? item.percentage : 0;
            } else {
              // 如果无法获取名称，根据数值确定大小
              const value = val[2] || 0;
              percentage = (value / maxValue) * 100;
            }

            // 根据百分比确定大小
            if (percentage > 15) return 25; // 主要省份较大
            if (percentage > 10) return 20; // 次要省份中等
            if (percentage > 5) return 15; // 一般省份适中
            return 10; // 其他省份较小
          } else {
            // 广西地图标记
            const value = val[2] || 0;
            return Math.min(22, 12 + (value / maxValue) * 15);
          }
        },
        label: {
          show: true,
          formatter: function (params) {
            // 安全地获取数据项
            const item = data.find((d) => d.name === params.name);

            // 标签显示规则
            if (mapType.value === "china") {
              // 全国地图,显示主要省份名称和销售额
              if (item && item.percentage > 7) {
                // 主要省份显示名称和数值
                const shortValue =
                  item.value >= 10000
                    ? (item.value / 10000).toFixed(1) + "w"
                    : item.value.toLocaleString();
                return `${params.name}\n${shortValue}`;
              } else if (item && item.percentage > 3) {
                // 次要省份仅显示名称
                return params.name;
              }
              return "";
            } else {
              // 广西地图显示主要城市名称和销售额
              if (item && item.percentage > 10) {
                const shortValue =
                  item.value >= 10000
                    ? (item.value / 10000).toFixed(1) + "w"
                    : item.value.toLocaleString();
                return `${params.name}\n${shortValue}`;
              } else if (item && item.percentage > 5) {
                return params.name;
              }
              return "";
            }
          },
          position: "inside",
          color: "#fff",
          fontSize: mapType.value === "china" ? 9 : 10,
          fontWeight: "bold",
          textShadow: "1px 1px 2px rgba(0, 0, 0, 0.6)",
        },
        itemStyle: {
          color: function (params) {
            // 根据数据值显示不同颜色
            const item = data.find((d) => d.name === params.name);
            if (!item) return "#FFB700";

            const percentage = item.percentage || 0;
            // 更精细的颜色分级
            if (percentage > 20) return "#FF4500"; // 特高值红色
            if (percentage > 15) return "#FF5722"; // 高值橙红色
            if (percentage > 10) return "#FF7043"; // 中高值橙色
            if (percentage > 5) return "#FF9800"; // 中值琥珀色
            if (percentage > 3) return "#FFC107"; // 中低值金色
            return "#FFD54F"; // 低值浅黄色
          },
          shadowColor: "rgba(0, 0, 0, 0.5)",
          shadowBlur: 5,
        },
        // 只显示主要省份/城市的标记
        data: data
          // 全国地图显示所有省份，广西地图显示所有城市
          .filter((item) => true)
          .map((item) => {
            return {
              name: item.name,
              value: [0, 0, item.value, item.name], // 添加名称作为第四个值，便于引用
              percentage: item.percentage, // 确保百分比也可访问
            };
          }),
        zlevel: 2,
      },
    ],
  };

  // 如果是中国地图，添加南海诸岛配置
  if (mapType.value === "china") {
    // 添加南海诸岛子地图配置
    option.series.push({
      name: "南海诸岛",
      type: "map",
      map: "china",
      // 调整南海诸岛位置，放在海南省右侧下方
      layoutCenter: ["85%", "90%"],
      layoutSize: "12%",
      itemStyle: {
        borderColor: "#fff",
        borderWidth: 1,
        areaColor: "#f3f4f5",
        shadowColor: "rgba(0, 0, 0, 0.15)",
        shadowBlur: 5,
      },
      emphasis: {
        itemStyle: {
          areaColor: "#0D5EFF",
        },
        label: {
          show: false,
        },
      },
      label: {
        show: false,
      },
      // 只显示南海诸岛部分
      select: {
        label: {
          show: false,
        },
      },
      roam: false,
      // 使用特殊样式来明确显示这是分离的南海区域
      tooltip: {
        show: false,
      },
    });

    // 添加南海标题标签
    option.graphic = [
      {
        type: "text",
        right: "7%",
        bottom: "6%",
        style: {
          text: "南海诸岛",
          textAlign: "center",
          fill: "#666",
          fontSize: 12,
        },
      },
      {
        type: "rect",
        right: "7%",
        bottom: "8%",
        z: 100,
        shape: {
          width: 60,
          height: 30,
        },
        style: {
          fill: "transparent",
          stroke: "#ccc",
          lineWidth: 1,
        },
      },
    ];
  }

  regionChart.setOption(option);
};

// 监听销售地区时间范围变化
watch(regionTimeRange, (newValue) => {
  nextTick(() => {
    initRegionChart();
  });
});

// 监听地图类型变化
watch(mapType, (newValue) => {
  nextTick(() => {
    initRegionChart();
  });
});

// 生成AI分析
const generateAIAnalysis = async () => {
  aiAnalysisLoading.value = true;
  try {
    // 模拟调用Deepseek API的延迟
    await new Promise((resolve) => setTimeout(resolve, 1500));

    // 这里是模拟的AI分析结果，实际实现中应该调用Deepseek API
    const analysisResults = [
      "根据您的商户数据分析，建议您关注以下几点：1) 周末销售额比工作日高出35%，可适当增加周末促销活动；2) 商品A、B类别利润率较高但销量偏低，建议调整营销策略增加曝光；3) 回头客占比仅为20%，低于行业平均，可建立会员积分体系增强顾客黏性；4) 近期订单中，移动端占比已达65%，建议优化移动端体验，提高便捷性。",
      "数据显示您的店铺有明显的销售季节性，暑期销量较高，建议提前1-2个月开始备货和营销规划。客户分析显示25-35岁消费者贡献了最高销售额，建议针对此群体定制产品和活动。线上订单退款率高于行业平均，主要原因是产品描述与实际不符，建议优化产品展示和描述。高价值商品转化率较低，可考虑提供分期付款选项增加销售。",
      "AI分析发现三个关键改进机会：首先，您的热销商品库存周转率低，建议优化供应链管理；其次，促销活动后的客户留存率不足，可通过个性化推荐提高复购；第三，评价数据显示顾客对配送时间满意度低，建议重新评估物流合作伙伴。数据还表明，您的商品平均利润率低于行业5个百分点，可考虑适当调整定价策略，或开发高附加值产品线。",
    ];

    // 随机选择一条分析结果
    aiAnalysisResult.value =
      analysisResults[Math.floor(Math.random() * analysisResults.length)];
    aiAnalysisTime.value = new Date().toLocaleString();

    // 保存到本地存储
    localStorage.setItem(
      "merchantAIAnalysis",
      JSON.stringify({
        result: aiAnalysisResult.value,
        time: aiAnalysisTime.value,
      }),
    );

    ElMessage.success("AI分析完成");
  } catch (error) {
    console.error("AI分析失败:", error);
    ElMessage.error("AI分析生成失败，请稍后重试");
  } finally {
    aiAnalysisLoading.value = false;
  }
};

// 添加商户运营指标五角图初始化代码
const businessIndicatorRef = ref(null);
let businessIndicatorChart = null;

// 初始化商户运营指标五角图
const initBusinessIndicatorChart = () => {
  if (!businessIndicatorRef.value) return;
  businessIndicatorChart = echarts.init(businessIndicatorRef.value);

  const option = {
    tooltip: {
      trigger: "item",
      backgroundColor: "rgba(255, 255, 255, 0.9)",
      borderColor: "#f2f3f5",
      borderWidth: 1,
      textStyle: {
        color: "#1d2129",
      },
    },
    legend: {
      data: ["当前值", "行业平均"],
      bottom: "5%",
      left: "center",
      itemWidth: 12,
      itemHeight: 12,
      itemGap: 20,
    },
    radar: {
      indicator: [
        { name: "平均订单金额", max: 200 },
        { name: "复购率", max: 100 },
        { name: "订单转化率", max: 30 },
        { name: "客单价增长率", max: 15 },
        { name: "客户满意度", max: 5 },
      ],
      shape: "polygon",
      center: ["50%", "55%"],
      radius: "65%",
      axisName: {
        color: "#4e5969",
        fontSize: 12,
      },
      splitArea: {
        areaStyle: {
          color: ["#f7f8fa", "#e1e6f0"],
          shadowColor: "rgba(0, 0, 0, 0.05)",
          shadowBlur: 10,
        },
      },
      axisLine: {
        lineStyle: {
          color: "rgba(220, 220, 220, 0.5)",
        },
      },
      splitLine: {
        lineStyle: {
          color: "rgba(220, 220, 220, 0.5)",
        },
      },
    },
    series: [
      {
        name: "商户运营指标",
        type: "radar",
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "rgba(22, 93, 255, 0.7)" },
            { offset: 1, color: "rgba(22, 93, 255, 0.1)" },
          ]),
        },
        lineStyle: {
          width: 2,
          color: "rgb(var(--primary-6))",
        },
        data: [
          {
            value: [156.8, 32.5, 18.3, 8.7, 4.5],
            name: "当前值",
            symbol: "circle",
            symbolSize: 6,
            itemStyle: {
              color: "rgb(var(--primary-6))",
            },
          },
          {
            value: [142.2, 28.0, 15.5, 5.2, 4.2],
            name: "行业平均",
            symbol: "circle",
            symbolSize: 6,
            lineStyle: {
              width: 2,
              color: "#FF7D00",
              type: "dashed",
            },
            itemStyle: {
              color: "#FF7D00",
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgba(255, 125, 0, 0.3)" },
                { offset: 1, color: "rgba(255, 125, 0, 0.1)" },
              ]),
            },
          },
        ],
      },
    ],
  };

  businessIndicatorChart.setOption(option);
};

onMounted(async () => {
  // 初始化数据
  orderStats.value = [
    { type: "total", label: "总订单数", value: 1580 },
    { type: "pending", label: "待处理", value: 32 },
    { type: "processing", label: "处理中", value: 58 },
    { type: "completed", label: "已完成", value: 1490 },
  ];

  // 加载本地存储的AI分析结果
  const savedAnalysis = localStorage.getItem("merchantAIAnalysis");
  if (savedAnalysis) {
    try {
      const analysisData = JSON.parse(savedAnalysis);
      aiAnalysisResult.value = analysisData.result;
      aiAnalysisTime.value = analysisData.time;
    } catch (e) {
      console.error("解析本地AI分析数据失败:", e);
    }
  }

  // 注册地图数据
  try {
    // 使用 china geo json 数据
    fetch("https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json")
      .then((res) => res.json())
      .then((chinaJson) => {
        echarts.registerMap("china", chinaJson);
      });

    // 使用广西 geo json 数据
    fetch("https://geo.datav.aliyun.com/areas_v3/bound/450000_full.json")
      .then((res) => res.json())
      .then((guangxiJson) => {
        echarts.registerMap("guangxi", guangxiJson);
      });
  } catch (error) {
    console.error("加载地图数据失败:", error);
  }

  // 模拟加载数据
  setTimeout(async () => {
    loading.value = false;
    showAnimation.value = true;
    await nextTick();
    initSalesChart();
    initOrderChart();
    initUserChart();
    initCategoryChart();
    initRegionChart();
    initBusinessIndicatorChart(); // 初始化商户运营指标五角图
  }, 1000);

  window.addEventListener("resize", handleResize);
});

// 组件卸载时销毁图表实例
onUnmounted(() => {
  salesChart?.dispose();
  orderChart?.dispose();
  userChart?.dispose();
  categoryChart?.dispose();
  regionChart?.dispose();
  businessIndicatorChart?.dispose();
  window.removeEventListener("resize", handleResize);
});

// 处理窗口大小变化
const handleResize = () => {
  salesChart?.resize();
  orderChart?.resize();
  userChart?.resize();
  categoryChart?.resize();
  regionChart?.resize();
  businessIndicatorChart?.resize(); // 添加商户运营指标图表的大小调整
};

// 添加热销商品趋势数据
const hotProducts = ref([
  { name: "特色桂花糕", sales: 328, trend: 12.5 },
  { name: "贵港荔枝礼盒", sales: 286, trend: 8.2 },
  { name: "文创手工艺品", sales: 256, trend: -5.8 },
  { name: "特产组合礼盒", sales: 198, trend: 4.3 },
  { name: "贵港特色小吃套装", sales: 176, trend: 15.6 },
]);
</script>

<style lang="less" scoped>
.merchant-dashboard {
  padding: 16px;

  .overview-card {
    height: 140px;

    .card-content {
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }

    .card-header {
      display: flex;
      align-items: center;
      gap: 8px;

      .card-title {
        font-size: 14px;
        color: var(--color-text-2);
      }

      .info-icon {
        color: var(--color-text-3);
        font-size: 14px;
        cursor: help;
      }
    }

    .card-value {
      font-size: 28px;
      font-weight: 600;
      color: var(--color-text-1);
      background: linear-gradient(
        45deg,
        rgb(var(--primary-6)),
        rgb(var(--success-6))
      );
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;

      .card-unit {
        font-size: 14px;
        font-weight: normal;
        margin-left: 4px;
        color: var(--color-text-3);
      }
    }

    .card-compare {
      font-size: 13px;
      color: var(--color-text-3);

      .trend-up {
        color: rgb(var(--success-6));
      }

      .trend-down {
        color: rgb(var(--danger-6));
      }
    }
  }

  .chart-card {
    height: 400px;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
    }

    .chart-container {
      height: 320px;
    }
  }

  .rank-card {
    height: 400px;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
    }

    .rank-list {
      margin-top: 16px;
    }

    .rank-item {
      display: flex;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid var(--color-border);
      transition: all 0.3s ease;

      &:last-child {
        border-bottom: none;
      }

      &:hover {
        background: var(--color-fill-2);
        transform: translateX(4px);
      }

      .rank-number {
        width: 20px;
        height: 20px;
        line-height: 20px;
        text-align: center;
        border-radius: 10px;
        font-size: 12px;
        margin-right: 12px;
        background-color: var(--color-fill-2);
        color: var(--color-text-2);

        &.rank-1 {
          background-color: #ffd700;
          color: #fff;
        }

        &.rank-2 {
          background-color: #c0c0c0;
          color: #fff;
        }

        &.rank-3 {
          background-color: #cd7f32;
          color: #fff;
        }
      }

      .rank-info {
        flex: 1;
        display: flex;
        flex-direction: column;

        .rank-name {
          font-size: 14px;
          color: var(--color-text-1);
        }

        .rank-category {
          font-size: 12px;
          color: #86909c;
          margin-left: 4px;
        }
      }

      .rank-value {
        font-size: 14px;
        color: var(--color-text-2);
      }
    }
  }

  .todo-card {
    height: 400px;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
    }

    .todo-list {
      margin-top: 16px;
    }

    .todo-item {
      display: flex;
      align-items: center;
      padding: 16px;
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        transform: translateX(4px);
        background: var(--color-fill-2);
      }

      .arco-badge {
        flex: 1;
      }

      .todo-count {
        font-size: 14px;
        font-weight: 500;
        color: var(--color-text-1);
        margin: 0 12px;
      }

      .todo-arrow {
        color: var(--color-text-3);
        font-size: 14px;
      }
    }
  }

  .order-stats {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 24px;
    margin-top: 24px;
    padding: 16px 24px;
    background: var(--color-bg-2);
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

    .stat-item {
      text-align: center;
      padding: 16px;
      border-radius: 8px;
      background: var(--color-bg-1);
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      }

      .stat-label {
        font-size: 14px;
        color: var(--color-text-3);
        margin-bottom: 8px;
        display: block;
      }

      .stat-value {
        font-size: 28px;
        font-weight: 600;
        color: var(--color-text-1);
        margin: 8px 0;
        background: linear-gradient(
          45deg,
          rgb(var(--primary-6)),
          rgb(var(--success-6))
        );
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        font-family: Arial, sans-serif;
      }
    }
  }

  .stats-card {
    height: auto;
    margin-bottom: 16px;

    .order-stats-vertical {
      display: flex;
      flex-direction: column;
      gap: 16px;
      padding: 8px;

      .stat-item {
        padding: 16px;
        border-radius: 8px;
        background: var(--color-bg-1);
        transition: all 0.3s ease;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

        &:hover {
          transform: translateX(-4px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        }

        .stat-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;

          .stat-label {
            font-size: 14px;
            color: var(--color-text-2);
          }
        }

        .stat-value {
          font-size: 28px;
          font-weight: 600;
          color: var(--color-text-1);
          margin: 8px 0;
          background: linear-gradient(
            45deg,
            rgb(var(--primary-6)),
            rgb(var(--success-6))
          );
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          font-family: Arial, sans-serif;
        }

        .stat-chart {
          height: 4px;
          background: var(--color-fill-2);
          border-radius: 2px;
          overflow: hidden;
          margin-top: 8px;

          .progress-bar {
            height: 100%;
            background: linear-gradient(
              90deg,
              rgb(var(--primary-6)),
              rgb(var(--success-6))
            );
            border-radius: 2px;
            transition: width 0.3s ease;
          }
        }
      }
    }
  }

  .mt-4 {
    margin-top: 16px;
  }

  /* 地图相关样式 */
  .flex {
    display: flex;
  }

  .items-center {
    align-items: center;
  }

  .justify-between {
    justify-content: space-between;
  }

  .map-chart-card {
    height: 500px;
  }

  .map-container {
    height: 420px !important;
  }

  /* 数据概览卡片样式 */
  .data-overview-cards {
    margin-bottom: 24px;

    .stat-card {
      transition: all 0.3s ease;
      height: 100%;
      border: none;
      border-radius: 8px;
      overflow: hidden;

      &:hover {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        transform: translateY(-2px);
      }

      .stat-icon {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 48px;
        height: 48px;
        border-radius: 12px;
        font-size: 24px;
      }

      &.revenue-card {
        background-color: #e8f3ff;
        border-left: 4px solid #165dff;

        .stat-icon {
          color: #4080ff;
          background-color: #d6e9ff;
        }
      }

      &.orders-card {
        background-color: #e8ffea;
        border-left: 4px solid #00b42a;

        .stat-icon {
          color: #00b42a;
          background-color: #d9f5de;
        }
      }

      &.visits-card {
        background-color: #f5e8ff;
        border-left: 4px solid #722ed1;

        .stat-icon {
          color: #722ed1;
          background-color: #eed6ff;
        }
      }

      &.members-card {
        background-color: #fff3e8;
        border-left: 4px solid #ff7d00;

        .stat-icon {
          color: #ff7d00;
          background-color: #ffe4cc;
        }
      }

      &.users-card {
        background-color: #fff3e8;
        border-left: 4px solid #ff7d00;

        .stat-icon {
          color: #ff7d00;
          background-color: #ffe4cc;
        }
      }

      .stat-footer {
        border-top: 1px solid rgba(0, 0, 0, 0.06);
        padding-top: 8px;
        margin-top: 12px;
      }
    }
  }
}

// 响应式布局
@media screen and (max-width: 1200px) {
  .merchant-dashboard {
    .overview-card {
      margin-bottom: 16px;
    }

    .chart-card {
      .chart-container {
        height: 280px;
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .merchant-dashboard {
    .chart-card,
    .rank-card,
    .todo-card {
      margin-bottom: 16px;

      .chart-container {
        height: 240px;
      }
    }
  }
}

// 添加暗色主题支持
:deep([arco-theme="dark"]) {
  .merchant-dashboard {
    .order-stats {
      background: var(--color-bg-2);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);

      .stat-item {
        background: var(--color-bg-3);
      }
    }

    .chart-card,
    .overview-card,
    .rank-card,
    .todo-card {
      &:hover {
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
      }
    }

    .data-overview-cards {
      .stat-card {
        .stat-footer {
          border-top: 1px solid rgba(255, 255, 255, 0.06);
        }

        &.revenue-card {
          background-color: rgba(22, 93, 255, 0.2);
        }

        &.orders-card {
          background-color: rgba(0, 180, 42, 0.2);
        }

        &.visits-card {
          background-color: rgba(114, 46, 209, 0.2);
        }

        &.members-card {
          background-color: rgba(255, 125, 0, 0.2);
        }

        &.users-card {
          background-color: rgba(255, 125, 0, 0.2);
        }
      }
    }

    .dashboard-actions {
      background-color: var(--color-bg-3);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);

      .reset-btn {
        border-color: var(--color-neutral-4);
        color: var(--color-text-2);

        &:hover {
          color: rgb(var(--primary-5));
          border-color: rgb(var(--primary-5));
          background-color: rgba(var(--primary-6), 0.15);
        }
      }
    }
  }
}

/* AI分析模块样式 */
.ai-analysis-card {
  transition: all 0.3s ease;
  margin-top: 16px;
}

.ai-analysis-card:hover {
  transform: translateY(-2px);
  box-shadow:
    0 6px 16px -8px rgba(0, 0, 0, 0.1),
    0 9px 28px 0 rgba(0, 0, 0, 0.05);
}

.ai-analysis-content {
  min-height: 120px;
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .dark-mode-styles {
    /* 保留这个选择器但移除特定样式 */
  }
}

.ai-card {
  height: 325px;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  }

  .ai-analysis-content {
    height: calc(100% - 110px);
    overflow-y: auto;
    padding: 8px;

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: rgba(0, 0, 0, 0.1);
      border-radius: 3px;
    }

    &::-webkit-scrollbar-track {
      background-color: transparent;
    }
  }
}
</style>
